package com.iwish.server.model;
import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

import com.iwish.server.storage.DAO.UserDAO;
import com.iwish.server.util.RequestParser;


public class ServerServicHandler implements IoHandler
{
	Logger logger = Logger.getLogger(ServerServicHandler.class);

	@Override
	public void exceptionCaught(IoSession session, Throwable exp)
			throws Exception {
		session.close(true);
	}

	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {

		String request = message.toString();
		logger.debug("messageReceive - request: " + request);
		RequestParser rp = new RequestParser(request);
		
		String request_code = rp.getRequest_code();
		String[] request_arr = rp.getArr();
		logger.debug("messageReceive - request code: " + request_code);
		RequestDispatcher rd = new RequestDispatcher(request_code, request_arr);
		rd.dispatch(session);
		
//		if(!(message instanceof IoBuffer) )
//		{
//			System.out.println("message is not instance of IoBuffer");
//			return;
//		}
//	
//		MessagePacket mp = (MessagePacket) message;
//		//request code = login
//		if(RequestCode.LOGIN == mp.getCode())
//		{
//			String cookie = mp.getCookie();
//			
//			User u = (User)mp.getData();
//			
//			LoginService ls = new LoginService(u,cookie);
//			if(ls.login())
//			{
//				//login success
//				System.out.println("user:" + u.getUsername() + " login success, session id = " + session.getId());
//				session.write("login success, session id = " + session.getId());
//			}
//			else
//			{
//				//login fail
//				System.out.println("user:" + u.getUsername() + " login fail...");
//				session.write("login fail, password unvalid...");
//			}
//		}
//		else if(RequestCode.REGISTER == mp.getCode())
//		{
//			
//		}
//		else if(RequestCode.UPDATE == mp.getCode())
//		{
//			
//		}
		
	}

	@Override
	public void messageSent(IoSession session, Object arg1) throws Exception {
		//System.out.println("Sent back login result");
	}

	@Override
	public void sessionClosed(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionCreated(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sessionOpened(IoSession arg0) throws Exception {
		// TODO Auto-generated method stub
		
	}

	

}
